package com.xie.o2o.service.impl;

import com.xie.o2o.dao.PersonInfoDao;
import com.xie.o2o.dao.WechatAuthDao;
import com.xie.o2o.dto.WechatAuthExecution;
import com.xie.o2o.entity.PersonInfo;
import com.xie.o2o.entity.WechatAuth;
import com.xie.o2o.enums.WechatAuthStateEnum;
import com.xie.o2o.service.WechatAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @create: xie
 */
@Service
public class WechatAuthServiceImpl implements WechatAuthService {
    @Autowired
    private WechatAuthDao wechatAuthDao;

    @Autowired
    private PersonInfoDao personInfoDao;

    @Override
    public WechatAuth getWechatAuthByOpenId(String openId) {
        return wechatAuthDao.queryWechatInfoByOpenId(openId);
    }

    @Override
    public WechatAuthExecution register(WechatAuth wechatAuth) throws RuntimeException {
        //空值判断
        if (wechatAuth == null && wechatAuth.getOpenId() == null) {
            return new WechatAuthExecution(WechatAuthStateEnum.NULL_AUTH_INFO);
        }
        try {
            wechatAuth.setCreateTime(new Date());
            //如果微信账号里带着用户信息并且用户id为空，则认为是该用户第一次使用平台（且通过微信登录）
            //则自动创建用户信息
            if (wechatAuth.getPersonInfo() != null && wechatAuth.getPersonInfo().getUserId() == null) {
                try {
                    wechatAuth.getPersonInfo().setCreateTime(new Date());
                    wechatAuth.getPersonInfo().setEnableStatus(1);
                    PersonInfo personInfo = wechatAuth.getPersonInfo();
                    int i = personInfoDao.insertPersonInfo(personInfo);
                    wechatAuth.setPersonInfo(personInfo);
                    if (i < 0) {
                        throw new RuntimeException("添加用户信息失败");
                    }
                } catch (Exception e) {
                    throw new RuntimeException("insetPersonInfo error:" + e.getMessage());
                }
            }
            //创建专属于本平台的账号
            int i = wechatAuthDao.insertWechatAuth(wechatAuth);
            if (i < 0) {
                throw new RuntimeException("创建账号失败");
            } else {
                return new WechatAuthExecution(WechatAuthStateEnum.SUCCESS, wechatAuth);
            }
        } catch (Exception e) {
            throw new RuntimeException("insetWechatAuth error:" + e.getMessage());
        }
    }
}
